package com.one.common.utils;

import android.util.Base64;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * author zhulunjun
 * email  zhulunjun@qq.com
 * date   2018/8/4 下午5:23
 * description rsa加密
 **/
public class RSAUtils {

    /**
     * RSA算法
     */
    public static final String RSA = "RSA";
    /**
     * 加密方式，标准jdk的
     */
    public static final String TRANSFORMATION = "RSA/None/PKCS1Padding";
    private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4L/7MhR99+yswtvSr0dKenD/oJUaow2AEJ6OYn2n12Y4H9RIQY2W5Sr/h4iwMzQTpWFNT5y7jjpGY+qYNQOR1GS6bG2GuTMK9W1BwC41y2gd0xwqWV+df2+S9eHqxqOdib/4/+t2JYxLTJvAC5pGPEvt3z8RXmO8mvtlVzBLaZQIDAQAB";

    /**
     * 使用公钥加密
     */
    public static String encryptByPublicKey(String data) {
        try {
            // 加密数据
            Cipher cp = Cipher.getInstance(TRANSFORMATION);
            cp.init(Cipher.ENCRYPT_MODE, loadPublicKey());
            return Base64.encodeToString(cp.doFinal(data.getBytes()), Base64.DEFAULT);
        } catch (Exception e) {
            Logger.e("加密失败 "+data);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从字符串中加载公钥
     *
     * @throws Exception
     *             加载公钥时产生的异常
     */
    public static PublicKey loadPublicKey() throws Exception
    {
        try
        {
            byte[] buffer = Base64.decode(publicKey, Base64.DEFAULT);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e)
        {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e)
        {
            throw new Exception("公钥非法");
        } catch (NullPointerException e)
        {
            throw new Exception("公钥数据为空");
        }
    }



}
